package com.chs.recoginition.controller;

import com.chs.recoginition.core.exception.ApplicationException;
import com.chs.recoginition.vo.respVo.UserRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


import static com.chs.recoginition.core.exception.constant.ExceptionConstant.UNAUTHORIZED;


@Slf4j
public class BaseController {

    /**
     * 获取当前用户id
     */
    protected Integer getUserOpenId() {
        // 开发环境从url获取用户id
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.getPrincipal() instanceof UserRespVo) {
            UserRespVo user = (UserRespVo) auth.getPrincipal();
            return user.getUserId();
        } else {
            return null;
        }
    }

    /**
     * 获取当前用户名
     */
    protected String getUsername() {
        return this.getUser().getNickname();
    }

    /**
     * 获取当前用户
     */
    protected UserRespVo getUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.getPrincipal() instanceof UserRespVo) {
            return (UserRespVo) auth.getPrincipal();
        } else {
            throw new ApplicationException(UNAUTHORIZED);
        }
    }


}
